import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import '../../core/constants.dart';
import '../../shared/models/daily_quiz.dart';
import '../../shared/providers/quiz_provider.dart';


class DailyQuizResultPage extends ConsumerWidget {
  final DailyQuiz quiz;
  final int totalQuestions;
  final int correctAnswers;
  final Duration duration;
  final double accuracy;

  const DailyQuizResultPage({
    super.key,
    required this.quiz,
    required this.totalQuestions,
    required this.correctAnswers,
    required this.duration,
    required this.accuracy,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      backgroundColor: const Color(0xFFF8F9FA),
      appBar: AppBar(
        title: const Text('Quiz Complete'),
        centerTitle: true,
        elevation: 0,
        backgroundColor: Colors.transparent,
        foregroundColor: AppConstants.DARK_BLUE,
        leading: const SizedBox(), // 隐藏返回按钮，强制用户通过底部按钮退出
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(24),
          child: Column(
            children: [
              _buildResultHeader(),
              const SizedBox(height: 32),
              _buildResultStats(),
              const SizedBox(height: 32),
              _buildPerformanceCard(),
              const SizedBox(height: 32),
              _buildActionButtons(context, ref),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildResultHeader() {
    final isExcellent = accuracy >= 0.9;
    final isGood = accuracy >= 0.7;
    
    Color headerColor;
    IconData headerIcon;
    String headerTitle;
    String headerSubtitle;
    
    if (isExcellent) {
      headerColor = Colors.amber;
      headerIcon = FontAwesomeIcons.trophy;
      headerTitle = 'Excellent!';
      headerSubtitle = 'Outstanding performance today!';
    } else if (isGood) {
      headerColor = Colors.green;
      headerIcon = FontAwesomeIcons.medal;
      headerTitle = 'Well Done!';
      headerSubtitle = 'Great job on today\'s quiz!';
    } else {
      headerColor = Colors.blue;
      headerIcon = FontAwesomeIcons.circleCheck;
      headerTitle = 'Quiz Complete!';
      headerSubtitle = 'You finished today\'s challenge!';
    }

    return Column(
      children: [
        Container(
          width: 120,
          height: 120,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                headerColor,
                headerColor.withOpacity(0.8),
              ],
            ),
            shape: BoxShape.circle,
            boxShadow: [
              BoxShadow(
                color: headerColor.withOpacity(0.3),
                blurRadius: 20,
                offset: const Offset(0, 10),
              ),
            ],
          ),
          child: Center(
            child: FaIcon(
              headerIcon,
              color: Colors.white,
              size: 50,
            ),
          ),
        ),
        const SizedBox(height: 24),
        Text(
          headerTitle,
          style: const TextStyle(
            fontSize: 32,
            fontWeight: FontWeight.bold,
            color: AppConstants.DARK_BLUE,
          ),
        ),
        const SizedBox(height: 8),
        Text(
          headerSubtitle,
          style: TextStyle(
            fontSize: 16,
            color: Colors.grey[600],
          ),
          textAlign: TextAlign.center,
        ),
      ],
    );
  }

  Widget _buildResultStats() {
    return Container(
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 15,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: Column(
        children: [
          const Text(
            'Today\'s Results',
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
              color: AppConstants.DARK_BLUE,
            ),
          ),
          const SizedBox(height: 24),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildStatCard(
                'Questions',
                '$totalQuestions',
                FontAwesomeIcons.listCheck,
                Colors.blue,
              ),
              _buildStatCard(
                'Correct',
                '$correctAnswers',
                FontAwesomeIcons.circleCheck,
                Colors.green,
              ),
              _buildStatCard(
                'Accuracy',
                '${(accuracy * 100).toInt()}%',
                FontAwesomeIcons.bullseye,
                Colors.orange,
              ),
            ],
          ),
          const SizedBox(height: 20),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildStatCard(
                'Duration',
                '${duration.inMinutes}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}',
                FontAwesomeIcons.clock,
                Colors.purple,
              ),
              _buildStatCard(
                'Speed',
                '${(totalQuestions / (duration.inSeconds / 60)).toStringAsFixed(1)}/min',
                FontAwesomeIcons.gaugeHigh,
                Colors.red,
              ),
              _buildStatCard(
                'Wrong',
                '${totalQuestions - correctAnswers}',
                FontAwesomeIcons.xmark,
                Colors.grey,
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildStatCard(String label, String value, IconData icon, Color color) {
    return Column(
      children: [
        Container(
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(
            color: color.withOpacity(0.1),
            borderRadius: BorderRadius.circular(12),
          ),
          child: FaIcon(icon, color: color, size: 24),
        ),
        const SizedBox(height: 8),
        Text(
          value,
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey[600],
          ),
        ),
      ],
    );
  }

  Widget _buildPerformanceCard() {
    final wrongAnswers = totalQuestions - correctAnswers;
    final accuracyPercentage = (accuracy * 100).toInt();
    
    String performanceText;
    Color performanceColor;
    IconData performanceIcon;
    
    if (accuracyPercentage >= 90) {
      performanceText = 'Exceptional! You\'re mastering Esperanto vocabulary!';
      performanceColor = Colors.amber;
      performanceIcon = FontAwesomeIcons.star;
    } else if (accuracyPercentage >= 80) {
      performanceText = 'Great work! You\'re making excellent progress!';
      performanceColor = Colors.green;
      performanceIcon = FontAwesomeIcons.thumbsUp;
    } else if (accuracyPercentage >= 70) {
      performanceText = 'Good job! Keep practicing to improve further!';
      performanceColor = Colors.blue;
      performanceIcon = FontAwesomeIcons.handPeace;
    } else if (accuracyPercentage >= 60) {
      performanceText = 'Not bad! Focus on reviewing the words you missed.';
      performanceColor = Colors.orange;
      performanceIcon = FontAwesomeIcons.lightbulb;
    } else {
      performanceText = 'Keep practicing! Every quiz helps you learn more.';
      performanceColor = Colors.red;
      performanceIcon = FontAwesomeIcons.heart;
    }

    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            performanceColor.withOpacity(0.1),
            performanceColor.withOpacity(0.05),
          ],
        ),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          color: performanceColor.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Column(
        children: [
          Row(
            children: [
              Container(
                padding: const EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: performanceColor.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: FaIcon(
                  performanceIcon,
                  color: performanceColor,
                  size: 20,
                ),
              ),
              const SizedBox(width: 12),
              const Expanded(
                child: Text(
                  'Performance Feedback',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: AppConstants.DARK_BLUE,
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Text(
            performanceText,
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[700],
              height: 1.4,
            ),
          ),
          if (wrongAnswers > 0) ...[
            const SizedBox(height: 12),
            Text(
              'You missed $wrongAnswers question${wrongAnswers > 1 ? 's' : ''}. Consider reviewing those words!',
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey[600],
                fontStyle: FontStyle.italic,
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildActionButtons(BuildContext context, WidgetRef ref) {
    return Column(
      children: [
        SizedBox(
          width: double.infinity,
          child: ElevatedButton.icon(
            onPressed: () {
              // 返回首页，清除所有之前的页面
              Navigator.of(context).popUntil((route) => route.isFirst);
            },
            icon: const FaIcon(FontAwesomeIcons.house, size: 18),
            label: const Text(
              'Back to Home',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
              ),
            ),
            style: ElevatedButton.styleFrom(
              backgroundColor: AppConstants.PRIMARY_BLUE,
              foregroundColor: Colors.white,
              padding: const EdgeInsets.symmetric(vertical: 16),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(16),
              ),
              elevation: 2,
            ),
          ),
        ),
        const SizedBox(height: 12),
        SizedBox(
          width: double.infinity,
          child: OutlinedButton.icon(
            onPressed: () async {
              // 获取今日测验统计
              final service = ref.read(dailyQuizServiceProvider);
              final stats = await service.getDailyQuizStats();
              
              if (context.mounted) {
                _showStatsDialog(context, stats);
              }
            },
            icon: const FaIcon(FontAwesomeIcons.chartLine, size: 18),
            label: const Text(
              'View Statistics',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
              ),
            ),
            style: OutlinedButton.styleFrom(
              foregroundColor: AppConstants.PRIMARY_BLUE,
              padding: const EdgeInsets.symmetric(vertical: 16),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(16),
              ),
              side: BorderSide(
                color: AppConstants.PRIMARY_BLUE.withOpacity(0.3),
                width: 1.5,
              ),
            ),
          ),
        ),
      ],
    );
  }

  void _showStatsDialog(BuildContext context, Map<String, dynamic> stats) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
          title: Row(
            children: [
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: AppConstants.PRIMARY_BLUE.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: const FaIcon(
                  FontAwesomeIcons.chartLine,
                  color: AppConstants.PRIMARY_BLUE,
                  size: 20,
                ),
              ),
              const SizedBox(width: 12),
              const Text(
                'Quiz Statistics',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: AppConstants.DARK_BLUE,
                ),
              ),
            ],
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              _buildStatsRow('Total Quizzes', '${stats['totalQuizzes']}', FontAwesomeIcons.listCheck),
              _buildStatsRow('Average Accuracy', '${(stats['averageAccuracy'] * 100).toInt()}%', FontAwesomeIcons.bullseye),
              _buildStatsRow('Best Accuracy', '${(stats['bestAccuracy'] * 100).toInt()}%', FontAwesomeIcons.trophy),
              _buildStatsRow('Current Streak', '${stats['currentStreak']} days', FontAwesomeIcons.fire),
              _buildStatsRow('Longest Streak', '${stats['longestStreak']} days', FontAwesomeIcons.medal),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text(
                'Close',
                style: TextStyle(
                  color: AppConstants.PRIMARY_BLUE,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ],
        );
      },
    );
  }

  Widget _buildStatsRow(String label, String value, IconData icon) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        children: [
          FaIcon(icon, size: 16, color: AppConstants.PRIMARY_BLUE),
          const SizedBox(width: 12),
          Expanded(
            child: Text(
              label,
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[700],
              ),
            ),
          ),
          Text(
            value,
            style: const TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.bold,
              color: AppConstants.DARK_BLUE,
            ),
          ),
        ],
      ),
    );
  }
} 